package com.xpq.petserver.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xpq.petserver.config.FilePathProperties;
import com.xpq.petserver.entity.R;
import com.xpq.petserver.entity.dto.PublicFosterageDTO;
import com.xpq.petserver.entity.dto.SearchBailmentDataDTO;
import com.xpq.petserver.entity.po.BailmentData;
import com.xpq.petserver.entity.po.Picture;
import com.xpq.petserver.entity.vo.BailmentDetailVO;
import com.xpq.petserver.entity.vo.MyFosterageVO;
import com.xpq.petserver.entity.vo.SearchBailmentDataVO;
import com.xpq.petserver.exception.AppException;
import com.xpq.petserver.exception.AppExceptionCodeMsg;
import com.xpq.petserver.mapper.BailmentDataMapper;
import com.xpq.petserver.mapper.PictureMapper;
import com.xpq.petserver.service.BailmentDataService;
import com.xpq.petserver.util.TimeUtli;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 寄养数据相关业务
 *
 * @author XPQ
 * @date 2022-05-03
 */
@Service
public class BailmentDataServiceImpl implements BailmentDataService {
    @Autowired
    private FilePathProperties filePathProperties;
    @Autowired
    private BailmentDataMapper bailmentDataMapper;
    @Autowired
    private PictureMapper pictureMapper;

    /**
     * 发布寄养消息业务
     *
     * @param multipartFiles
     * @param publicFosterageDTO
     * @return
     */
    @Override
    @Transactional
    public R publicFosterage(List<MultipartFile> multipartFiles, PublicFosterageDTO publicFosterageDTO) {
        // 整理寄养消息数据
        long bailmentDataId = System.currentTimeMillis();
        publicFosterageDTO.setId(bailmentDataId);
        publicFosterageDTO.setCreateTime(TimeUtli.getCurrentTime());
        publicFosterageDTO.setUpdateTime(TimeUtli.getCurrentTime());

        // 整理图片数据
        List<Picture> pictures = new ArrayList<>();
        for (int i = 0; i < multipartFiles.size(); i++) {
            Picture picture = new Picture();
            picture.setId(System.currentTimeMillis() + i);
            picture.setFilename(System.currentTimeMillis() + i + multipartFiles.get(i).getOriginalFilename());
            picture.setBailmentDataId(bailmentDataId);
            picture.setCreateTime(TimeUtli.getCurrentTime());
            picture.setUpdateTime(TimeUtli.getCurrentTime());
            pictures.add(picture);
        }

        try {
            // 向数据库添加数据和将文件存储到硬盘
            bailmentDataMapper.insertBailmentData(publicFosterageDTO);
            if (pictures.size() != 0) { // 此处可以改成批量插入数据库
                pictureMapper.insertPicture(pictures);
                // 判断文件夹是否存在
                File fileDir = new File(filePathProperties.getPicturePhysicalPath());
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                for (int i = 0; i < pictures.size(); i++) {
                    File file = new File(fileDir, pictures.get(i).getFilename());
                    boolean isSuccessfullyNewFile = file.createNewFile();
                    if (isSuccessfullyNewFile) {
                        multipartFiles.get(i).transferTo(file);
                    }
                }
            }
            return R.success("发布成功！");
        } catch (IOException e) {
            e.printStackTrace();
            throw new AppException(AppExceptionCodeMsg.UPLOAD_PICTURE_ERROR);
        }
    }

    /**
     * 获取用户寄养数据
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public R getMyFosterage(String userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MyFosterageVO> myFosterageVOs = bailmentDataMapper.selectMyFosterage(userId);
        PageInfo<MyFosterageVO> myFosterageVOPageInfo = new PageInfo<>(myFosterageVOs);
        // 获取每条寄养数据的第一张图片
        for (int i = 0; i < myFosterageVOPageInfo.getList().size(); i++) {
            String filename = pictureMapper.selectFistFilename(myFosterageVOPageInfo.getList().get(i).getId());
            if (filename != null) {
                myFosterageVOPageInfo.getList().get(i).setPicture(filePathProperties.getPictureLogicalPath() + filename);
            }
        }
        return R.success(myFosterageVOPageInfo);
    }

    /**
     * 获取寄养消息的详情信息
     *
     * @param id 寄养消息id
     * @return
     */
    @Override
    public R getBailmentDetail(Long id) {
        BailmentDetailVO bailmentDetailVO = bailmentDataMapper.selectBailmentDetail(id);
        List<String> filenames = pictureMapper.selectFilenames(id);
        for (int i = 0; i < filenames.size(); i++) {
            filenames.set(i, filePathProperties.getPictureLogicalPath() + filenames.get(i));
        }
        bailmentDetailVO.setPictures(filenames);
        return R.success(bailmentDetailVO);
    }

    /**
     * 删除寄养数据
     *
     * @param bailmentDataId 寄养数据id
     * @param userId         用户id
     * @return
     */
    @Override
    public R deleteBailmentData(Long bailmentDataId, String userId) {
        BailmentData bailmentData = bailmentDataMapper.selectBailmentData(bailmentDataId);
        // 要删除的数据的用户id和自己的id不一样，没有权限删除
        if (!(bailmentData.getUserId().equals(userId))) {
            throw new AppException(AppExceptionCodeMsg.NO_AUTH_DELETE_DATA);
        }
        // 删除图片文件
        List<String> filenames = pictureMapper.selectFilenames(bailmentDataId);
        for (int i = 0; i < filenames.size(); i++) {
            File file = new File(filePathProperties.getAvatarPhysicalPath() + filenames.get(i));
            file.delete();
        }
        // 删除数据库数据
        bailmentDataMapper.deleteBailmentData(bailmentDataId);
        return R.success("删除成功！", null);
    }

    /**
     * 搜索寄养数据业务
     *
     * @param searchBailmentDataDTO 搜索条件
     * @return
     */
    @Override
    public R searchBailmentData(SearchBailmentDataDTO searchBailmentDataDTO) {
        String keyWord = searchBailmentDataDTO.getKeyWord();
        // 如果关键词不为空,则在每个字符中间加上 % 进行模糊查询
        if (keyWord != null && !("".equals(keyWord))) {
            StringBuffer stringBuffer = new StringBuffer(keyWord);
            int length = stringBuffer.length();
            for (int i = 0; i < length + 1; i++) {
                stringBuffer.insert(2 * i, "%");
            }
            searchBailmentDataDTO.setKeyWord(stringBuffer.toString());
        }
            PageHelper.startPage(searchBailmentDataDTO.getPageNum(), searchBailmentDataDTO.getPageSize());
            List<SearchBailmentDataVO> searchBailmentDataVOs = bailmentDataMapper.selectSearchBailmentDataVO(searchBailmentDataDTO);
            PageInfo<SearchBailmentDataVO> searchBailmentDataVOPageInfo = new PageInfo<>(searchBailmentDataVOs);

            for (int i = 0; i < searchBailmentDataVOPageInfo.getList().size(); i++) {
                String filename = pictureMapper.selectFistFilename(searchBailmentDataVOPageInfo.getList().get(i).getId());
                searchBailmentDataVOPageInfo.getList().get(i).setPicture(filePathProperties.getPictureLogicalPath() + filename);
            }
            return R.success(searchBailmentDataVOPageInfo);

    }
}
